package cn.iocoder.yudao.module.javainfo.service.pet;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.javainfo.controller.admin.userpet.vo.UserPetSaveReqVO;
import cn.iocoder.yudao.module.javainfo.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.javainfo.dal.dataobject.userpet.UserPetDO;
import cn.iocoder.yudao.module.javainfo.service.user.JavaInfoUserService;
import cn.iocoder.yudao.module.javainfo.service.userpet.UserPetService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.javainfo.controller.admin.pet.vo.*;
import cn.iocoder.yudao.module.javainfo.dal.dataobject.pet.PetDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.javainfo.dal.mysql.pet.PetMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.javainfo.enums.ErrorCodeConstants.*;

/**
 * 宠物 Service 实现类
 *
 * @author 爪哇国大BOSS
 */
@Service
@Validated
public class PetServiceImpl implements PetService {

    @Resource
    private PetMapper petMapper;

    @Resource
    private UserPetService userPetService;

    @Resource
    private JavaInfoUserService javaInfoUserService;

    @Override
    @Transactional
    public Long createPet(PetSaveReqVO createReqVO) {
        // 插入
        PetDO pet = BeanUtils.toBean(createReqVO, PetDO.class);
        petMapper.insert(pet);
        // 插入用户和宠物关系表
        insertUserPetRel(pet.getId(), createReqVO.getOwnerUserId());

        // 返回
        return pet.getId();
    }

    private void insertUserPetRel(Long id, @NotNull(message = "宠物归属用户ID不能为空") Long ownerUserId) {
        UserPetSaveReqVO userPetSaveReqVO = new UserPetSaveReqVO();
        // 校验用户是否存在并且可用
        validateUserExists(ownerUserId);
        userPetSaveReqVO.setUserId(ownerUserId);
        userPetSaveReqVO.setPetId(id);
        userPetService.createUserPet(userPetSaveReqVO);
    }

    private void validateUserExists(@NotNull(message = "宠物归属用户ID不能为空") Long ownerUserId) {
        UserDO user = javaInfoUserService.getUser(ownerUserId);
        if (user == null) {
            throw exception(JAVA_USER_NOT_EXISTS);
        }
        if (user.getDeleted()) {
            throw exception(JAVA_USER_DISABLE);
        }
    }

    @Override
    @Transactional
    public void updatePet(PetSaveReqVO updateReqVO) {
        // 校验存在
        validatePetExists(updateReqVO.getId());
        // 更新
        PetDO updateObj = BeanUtils.toBean(updateReqVO, PetDO.class);
        petMapper.updateById(updateObj);
        if (updateReqVO.getOwnerUserId() != null) {
            // 判断宠物所属用户是否变更
            UserPetDO userPet = userPetService.getUserPetByPetId(updateReqVO.getId());
            if (userPet.getUserId().equals(updateReqVO.getOwnerUserId())) {
                return;
            }
            userPetService.deleteUserPet(userPet.getId());
            // 插入用户和宠物关系表
            insertUserPetRel(updateReqVO.getId(), updateReqVO.getOwnerUserId());
        }

    }

    @Override
    @Transactional
    public void deletePet(Long id) {
        // 校验存在
        validatePetExists(id);
        // 删除
        petMapper.deleteById(id);
        // 删除用户宠物信息
        userPetService.deleteUserPetById(id);
    }

    @Override
    public void deletePetListByIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 删除
        petMapper.deleteByIds(ids);
        userPetService.deleteUserPetListByPetIds(ids);
    }


    private void validatePetExists(Long id) {
        if (petMapper.selectById(id) == null) {
            throw exception(JAVA_PAT_NOT_EXISTS);
        }
    }

    @Override
    public PetDO getPet(Long id) {
        return petMapper.selectById(id);
    }

    @Override
    public PageResult<PetRespVO> getPetPage(PetPageReqVO pageReqVO) {
        PageResult<PetDO> petDOPageResult = petMapper.selectPage(pageReqVO);
        PageResult<PetRespVO> beanResult = BeanUtils.toBean(petDOPageResult, PetRespVO.class);
        // 获取对应用户名称
        List<Long> userIds = CollUtil.emptyIfNull(beanResult.getList()).stream().map(PetRespVO::getOwnerUserId).collect(Collectors.toList());
        Map<Long, String> userId2NameMap = javaInfoUserService.getUserMap(userIds);
        // 拼接用户名称
        for (PetRespVO bean : beanResult.getList()) {
            bean.setOwnerUserName(userId2NameMap.get(bean.getOwnerUserId()));
        }
        return beanResult;
    }

}